//
//  HOnePageDetailViewController.m
//  ShowYork
//
//  Created by hxh on 2020/10/4.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "HomePageDetailViewController.h"
#import "HomePageTopicListViewController.h"

#import "HomePageDetailImageItemCell.h"
#import "HomePageContentDetailCell.h"
#import "HomePageDetailVideoItemCell.h"


#import "HomePageItemModel.h"
#import "HomePageMenuItemModel.h"
#import "HomePageContentModel.h"

#import "HomePageDetailControl.h"
#import "HomePageFollowMoreView.h"
#import "HomePageFeedbackView.h"
#import "HomePageMenuView.h"

#import "AppDelegate.h"
#import "HomePageCommentView.h"
#import "HomePageReplyItemModel.h"
#import "HomePageCommentItemModel.h"
#import "MineFollowItemModel.h"
#import "UserInfoFollowModel.h"
#import "RPAppShareView.h"
#import "HomePageDetailHeaderView.h"
#import "HomePageDetailNoDataView.h"

#import "UIImage+Circular.h"

NSString* const kXHItemType        = @"KXHItemType";
NSString* const kXHListSource      = @"KXHListSource";
NSString* const kXHCurrentIndex    = @"KXHCurrentIndex";
NSString* const kXHCurrentPage     = @"KXHCurrentPage";
NSString* const kXHPlatformType    = @"KXHPlatformType";
NSString* const kXHLikedUserId     = @"KXHLikedUserId";
NSString* const kXHDetailCommentId = @"KXHDetailCommentId";
NSString* const kXHDetailReplyId   = @"KXHDetailReplyId";
NSString* const kXHDetailTagId     = @"KXHDetailTagId";
NSString* const kXHShowUserInfo    = @"KXHShowUserInfo";
NSString* const kXHScrollUnEnable    = @"kXHScrollUnEnable";
NSString* const kXHHeaderHidden      = @"kXHHeaderHidden";
NSString* const kXHUserCreateTime  = @"kXHUserCreateTime";

@interface HomePageDetailViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,HomePageDetailImageItemCellDelegate,HomePageContentDetailCellDelegate,HomePageDetailVideoItemCellDelegate,HomePageCommentViewDelegate,HomePageDetailHeaderViewDelegate,HomePageDetailNoDataViewDelegate>

@property (nonatomic,strong)HomePageDetailHeaderView *headView; /// 头部视图
@property (nonatomic,strong)HomePageDetailNoDataView *noDataView; /// 没有数据的提示页面图片

@property (nonatomic,strong)UIView *helpCoverView; /// 新手引导的遮盖图
@property (nonatomic,strong)UIImageView *helpNextImgView; /// 新手引导的下一个提醒视图
@property (nonatomic,strong)UIImageView *helpRemoveImgView; /// 新手引导的关闭提醒视图
@property (nonatomic,strong)HomePageCommentView *commentView; /// 评论列表
@property (nonatomic,strong)ZFPlayerController *player; /// 视频播放器
@property (nonatomic,strong)HomePageDetailControl *fullControlView; /// 视频播放视图
@property (nonatomic,strong)UITableView *tableView; /// 列表

@property (nonatomic,strong)NSURLSessionTask *task; /// 请求的task 关闭重复的请求
@property (nonatomic,strong)NSURLSessionTask *task1; /// 是否点赞的task 防止用户恶意点击
@property (nonatomic,strong)NSURLSessionTask *task2; /// 是否点赞的task 防止用户恶意点击
@property (nonatomic,strong)NSURLSessionTask *followTask; /// 关注列表的task 关闭上次请求
@property (nonatomic,strong)NSURLSessionTask *likeTask; /// 获取指定用户的task 防止用户恶意点击

@property (nonatomic,strong)NSMutableArray *dataArray; /// 列表数据

@property (nonatomic,strong)HomePageItemModel *currentModel; /// 当前滑动对象
@property (nonatomic,strong)HomePageDetailVideoItemCell *currentVideoCell; /// 当前播放的视频cell

@property (nonatomic,strong)NSTimer *timer; /// 定时器用于增加观看次数

@property (nonatomic,assign)NSInteger userPageIndex; /// 用户查询列表的索引
@property (nonatomic,strong)NSMutableArray *userArray; /// 用户查看的list

@property (nonatomic,assign)XHPageDetailPlatformType type; /// 评论类型
@property (nonatomic,assign)XHPageDetailItemType itemType;

@property (nonatomic,strong)NSNumber *tagId; /// 标签id
@property (nonatomic,strong)NSNumber *commentId; /// 评论id
@property (nonatomic,strong)NSNumber *replyId; /// 回复id
@property (nonatomic,strong)NSNumber *likeUserInfoId; /// 点赞用户的id

@property (nonatomic,assign)BOOL isShow; /// 是否展示状态栏

@property (nonatomic,assign)BOOL isHideTool; /// 是否隐藏工具条
@property (nonatomic,assign)BOOL showUserInfo; /// 是否显示用户头像（暂时未使用）
@property (nonatomic,assign)BOOL scrollEnable;
@property (nonatomic,assign)BOOL showHeader;
@property (nonatomic,assign)BOOL showCreateTime;

@property (nonatomic,assign)NSInteger currentIndex; /// 当前对象的分页索引
@property (nonatomic,strong)NSNumber *playStatus; /// 播放状态

@property (nonatomic,assign)BOOL lastPage;


@property (nonatomic,strong)NSIndexPath *lastIndexPath;

@property (nonatomic,assign)BOOL isDraging;
@property (nonatomic,assign)BOOL isUpdateProgress;

@property (nonatomic,strong)UILabel *totalTimeLb;
@property (nonatomic,strong)UILabel *currenTimeLb;

@end

@implementation HomePageDetailViewController


- (void)viewWillAppear:(BOOL)animated{
    
    
    [super viewWillAppear:animated];
    
    if (self.type == XHPageDetailPlatformTypeMessageReply ||
        self.type == XHPageDetailPlatformTypeMessageComment ||
        self.type == XHPageDetailPlatformTypeMessageOther) {
        [self.navigationController setNavigationBarHidden:YES animated:YES];
    }else{
        self.navigationController.navigationBarHidden = YES;
    }
    
    [MobClick beginLogPageView:@"HomePageDetail"];
    
    if (!self.currentModel.readyPlay) {
        if (self.playStatus.intValue != 2) {
            [self.player.currentPlayerManager play];
        }else{
            [self.player.currentPlayerManager pause];
        }
    }

    self.player.viewControllerDisappear = NO;
    
    [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = NO;
    
    
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (self.type == XHPageDetailPlatformTypeMessageReply ||
        self.type == XHPageDetailPlatformTypeMessageComment ||
        self.type == XHPageDetailPlatformTypeMessageOther) {
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }else{
        self.navigationController.navigationBarHidden = NO;
    }
    
    if (!self.currentModel.readyPlay) {
        [self updatePlayerStatus];
        [self.player.currentPlayerManager pause];
        self.player.viewControllerDisappear = YES;
    }

    [MobClick endLogPageView:@"HomePageDetail"];
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    
    [self.timer invalidate];
    self.timer = nil;
}

- (HomePageDetailControl *)fullControlView {
    if (!_fullControlView) {
        _fullControlView = [[HomePageDetailControl alloc] init];
    }
    return _fullControlView;
}
- (NSMutableArray *)userArray{
    if (!_userArray) {
        _userArray = [NSMutableArray array];
    }
    return _userArray;
}


- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.pagingEnabled = YES;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.scrollsToTop = NO;
        _tableView.backgroundColor = [UIColor blackColor];
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.frame = self.view.bounds;
        _tableView.rowHeight = _tableView.frame.size.height;
        
    }
    return _tableView;
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (self.currentVideoCell == nil) {
        @zf_weakify(self)
        [self.player zf_filterShouldPlayCellWhileScrolled:^(NSIndexPath *indexPath) {
            @zf_strongify(self)
            [self playTheVideoAtIndexPath:indexPath scrollAnimated:NO];
        }];
    }
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (instancetype)initWithConfigInfo:(NSDictionary *)configInfo{
    if (self = [super init]) {
        // list列表
        [self.dataArray addObjectsFromArray:configInfo[kXHListSource]];
        // 当前index
        self.currentIndex = [configInfo[kXHCurrentIndex] intValue];
        // 当前选择对象
        self.currentModel = self.dataArray[self.currentIndex];
        // 进入类型
        self.type = [configInfo[kXHPlatformType] intValue];
        // 点赞用户id
        self.likeUserInfoId = configInfo[kXHLikedUserId];
        // 评论id
        self.commentId = configInfo[kXHDetailCommentId];
        // 用户id
        self.replyId = configInfo[kXHDetailReplyId];
        // 标签id
        self.tagId = configInfo[kXHDetailTagId];
        // 按钮类型
        self.itemType = [configInfo[kXHItemType]intValue];
        // 是否显示头像
        self.showUserInfo = [configInfo[kXHShowUserInfo] boolValue];
        // 全局字段
        self.scrollEnable = YES;
        // 是否显示底部时间
        self.showCreateTime = [configInfo[kXHUserCreateTime] boolValue];
        
        if (configInfo[kXHScrollUnEnable] != nil) {
            self.scrollEnable = ![configInfo[kXHScrollUnEnable] boolValue];
            self.tableView.scrollEnabled = self.scrollEnable;
        }
        self.showHeader = NO;
        if (configInfo[kXHHeaderHidden] != nil) {
            self.showHeader = [configInfo[kXHHeaderHidden] boolValue];
        }
        self.lastIndexPath = [NSIndexPath indexPathForRow:self.currentIndex inSection:0];
    }
    return self;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isHideTool = NO;
    [self setNormalData];
}

- (void)setNormalData{
    [self setUI];
    [self setupHeaderView];
    [self setupTimer];
    [self updatePageDetailNumber];
    [self setupRealDataSource];
    [self showCommentView];
    [self registNote];
}

- (void)showCommentView{
    // 这里要做处理 1、消息中心跳转 2、首页跳转
    if (self.type != XHPageDetailPlatformTypeNormal &&
        self.type != XHPageDetailPlatformTypeMineList &&
        self.type != XHPageDetailPlatformTypeUserList) {
//        [self.headView removeGradientLayer];
        if (self.type == XHPageDetailPlatformTypeMessageComment) {
            // 判断该条评论是否存在
            [self isExistCommentDetail];
        }else if (self.type == XHPageDetailPlatformTypeMessageReply) {
            // 判断该条回复是否存在
            [self isExistReplyDetail];
        }else if (self.type == XHPageDetailPlatformTypeHtml ||
                  self.type == XHPageDetailPlatformTypeMessageOther ||
                  self.type == XHPageDetailPlatformTypeSingleDetail){
            // 展示其他类型的新手引导
            [self setupOtherCoverView];
        }else{
            // 普通弹起评论回复面板
            self.commentView = [[HomePageCommentView alloc]initWithPlatformId:self.currentModel.postId platformType:self.type showCommentId:@0 showReplyId:@0];
            [self.commentView showBindVC:self delegate:self];
        }
    }else{
        // 展示首页进入的新手引导
        [self setupHelpCoverView];
    }
    
}

- (void)setUI{
    
    self.isUpdateProgress = YES;
    
    [self.view addSubview:self.tableView];
    /// playerManager
    ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
    self.player = [ZFPlayerController playerWithScrollView:self.tableView playerManager:playerManager containerViewTag:100];
    self.player.disableGestureTypes = ZFPlayerDisableGestureTypesPan | ZFPlayerDisableGestureTypesPinch;
    self.player.controlView = self.fullControlView;
    self.player.allowOrentitaionRotation = NO;
    self.player.WWANAutoPlay = YES;
    __weak typeof(self)weakSelf = self;
    // 赋值修改播放视频文本框隐藏的bug
    self.player.notification.willResignActive = ^(ZFPlayerNotification * _Nonnull registrar) {
        if (weakSelf.player.viewControllerDisappear) return;
        if (weakSelf.player.pauseWhenAppResignActive && weakSelf.player.currentPlayerManager.isPlaying) {
            weakSelf.player.pauseByEvent = YES;
        }
        weakSelf.player.orientationObserver.lockedScreen = YES;
        if (!weakSelf.player.pauseWhenAppResignActive) {
            [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
            [[AVAudioSession sharedInstance] setActive:YES error:nil];
        }
    };

    @zf_weakify(self)
    /// 更新另一个控制层的时间
    self.player.playerPlayTimeChanged = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSTimeInterval currentTime, NSTimeInterval duration) {
        @zf_strongify(self)
        if (!self.isDraging && self.isUpdateProgress) {
            self.currentModel.readyPlay = NO;
            [self.currentVideoCell updateProgressValue:self.player.progress];
        }
    };
    self.player.playerDidToEnd = ^(id  _Nonnull asset) {
        @zf_strongify(self)
        if (!self.player.viewControllerDisappear) {
            [self.player.currentPlayerManager replay];
        }
    };
    
    /// 停止的时候找出最合适的播放(只能找到设置了tag值cell)
    self.player.zf_scrollViewDidEndScrollingCallback = ^(NSIndexPath * _Nonnull indexPath) {
     
    };
    
    self.player.playerPlayFailed = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSError * _Nonnull error) {
        @zf_strongify(self)
        // 没有权限访问
        if (error.code == -1102) {
            if (self.task2 != nil && self.task2.state == NSURLSessionTaskStateRunning) {
                [self.task2 cancel];
            }
            [self showDataLoadState];
            HomePageItemModel *item = self.dataArray[self.lastIndexPath.item];
            NSMutableDictionary *parma = [NSMutableDictionary dictionary];
            parma[@"userId"] = [RPAppManager getCustomerId];
            parma[@"postId"] = item.postId;
            parma[@"md5"] = [RPAppManager md5StrWithApi:GetPostTargetDetail];
            self.task2 = [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetPostTargetDetail) parames:parma success:^(id responseObj) {
                [self hideDataLoadLoadState];
                HomePageItemModel *newModel = [HomePageItemModel mj_objectWithKeyValues:responseObj[RESPONSE]];
                // 重新赋值内容对象
                item.contents = newModel.contents;
                // 播放失败
                [self playTheVideoAtIndexPath:self.lastIndexPath scrollAnimated:NO];
                
            } failure:^(NSError *error) {
                self.currentModel.readyPlay = YES;
                [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
                [self hideDataLoadLoadState];
            }];
        }else{
            self.currentModel.readyPlay = YES;
            [WHToast showMessage:@"抱歉，播放出错了" duration:2 finishHandler:nil];
        }
        
    };
    self.player.zf_playerShouldPlayInScrollView = ^(NSIndexPath * _Nonnull indexPath) {
        @zf_strongify(self)
        if ([indexPath compare:self.player.playingIndexPath] != NSOrderedSame) {
            
            if (indexPath == nil) {
                return;
            }
            
            if (self.lastIndexPath.item != indexPath.item || self.lastIndexPath == nil) {
                if (self.task2 != nil && self.task2.state == NSURLSessionTaskStateRunning) {
                    [self.task2 cancel];
                }
                HomePageDetailVideoItemCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
                [cell resetProgressValue];
                
                self.lastIndexPath = indexPath;
                
                HomePageItemModel *item = self.dataArray[indexPath.item];
                NSMutableDictionary *parma = [NSMutableDictionary dictionary];
                parma[@"userId"] = [RPAppManager getCustomerId];
                parma[@"postId"] = item.postId;
                parma[@"md5"] = [RPAppManager md5StrWithApi:GetPostTargetDetail];
                self.task2 = [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetPostTargetDetail) parames:parma success:^(id responseObj) {
                    
                    HomePageItemModel *newModel = [HomePageItemModel mj_objectWithKeyValues:responseObj[RESPONSE]];
                    // 重新赋值内容对象
                    item.contents = newModel.contents;
                    // 播放失败
                    [self  playTheVideoAtIndexPath:indexPath scrollAnimated:NO];
                    
                } failure:^(NSError *error) {
                    
                }];
            
            }
        }
    };
    
    self.fullControlView.controlViewAppearedCallback = ^(BOOL appeared) {
        @zf_strongify(self)
        self.isHideTool = !appeared;
        if (appeared) {
            [self.currentVideoCell showFooterView];
        }else{
            [self.currentVideoCell hideFooterView];
            [MobClick event:@"homeDetail_hide_statusBar"];
        }
        
        [UIView animateWithDuration:0.25 animations:^{
            self.headView.cl_y = self.isHideTool?-kNavBarHeight:0;
        } completion:^(BOOL finished) {
            
        }];
    };
    self.fullControlView.controlViewPlayerStatusCallback = ^(BOOL status) {
        @zf_strongify(self)
        [self updatePlayerStatus];
    };
    
    [self.tableView setContentOffset:CGPointMake(0, kScreenH * self.currentIndex) animated:NO];
    
    self.tableView.backgroundColor = [UIColor blackColor];
    self.view.backgroundColor = [UIColor blackColor];
    
    self.isHideNavBar = YES;
    
    self.totalTimeLb = [[UILabel alloc]init];
    self.totalTimeLb.textColor = C153;
    self.totalTimeLb.font = font(14);
    self.totalTimeLb.alpha = 0;
    [self.view addSubview:self.totalTimeLb];
    
    [self.totalTimeLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).offset(kScreenW/2);
        make.bottom.equalTo(self.view).offset(-(90 + GK_SAVEAREA_BTM));
    }];
    
    self.currenTimeLb = [[UILabel alloc]init];
    self.currenTimeLb.textColor = [UIColor whiteColor];
    self.currenTimeLb.font = font(14);
    self.currenTimeLb.alpha = 0;
    [self.view addSubview:self.currenTimeLb];
    [self.currenTimeLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.totalTimeLb);
        make.right.equalTo(self.totalTimeLb.mas_left);
    }];
        
}



- (void)setupOtherCoverView{
    BOOL isFirstTypeUse = NO;
    NSString *imageName = nil;
    if (self.currentModel != nil) {
        if (self.currentModel.contentType.intValue == 1) {
            isFirstTypeUse = [[[NSUserDefaults standardUserDefaults] objectForKey:@"isFirstPageDetailContentHelp"]boolValue];
            imageName = @"home_next_text_tag";
        }else if (self.currentModel.contentType.intValue == 2) {
            isFirstTypeUse = [[[NSUserDefaults standardUserDefaults] objectForKey:@"isFirstPageDetailPictureHelp"]boolValue];
            imageName = @"home_next_img_tag";
        }else if (self.currentModel.contentType.intValue == 3) {
            isFirstTypeUse = [[[NSUserDefaults standardUserDefaults] objectForKey:@"isFirstPageDetailVideoHelp"]boolValue];
            imageName = @"home_video_stop_tag";
        }
        if (!isFirstTypeUse) {
            [self setCoverViewWithImg:imageName];
            self.isShow = YES;
        }
    }
}

#pragma mark - 设置新手引导图
- (void)setupHelpCoverView{
    self.isShow = NO;
    // 判断是否是第一次使用
    BOOL isFirstPageDetailUse = [[[NSUserDefaults standardUserDefaults] objectForKey:@"isFirstPageDetailUse"] boolValue];
    if (isFirstPageDetailUse) {
        BOOL isFirstTypeUse = NO;
        NSString *imageName = nil;
        if (self.currentModel != nil) {
            if (self.currentModel.contentType.intValue == 1) {
                isFirstTypeUse = [[[NSUserDefaults standardUserDefaults] objectForKey:@"isFirstPageDetailContentHelp"]boolValue];
                imageName = @"home_next_text_tag";
            }else if (self.currentModel.contentType.intValue == 2) {
                isFirstTypeUse = [[[NSUserDefaults standardUserDefaults] objectForKey:@"isFirstPageDetailPictureHelp"]boolValue];
                imageName = @"home_next_img_tag";
            }else if (self.currentModel.contentType.intValue == 3) {
                isFirstTypeUse = [[[NSUserDefaults standardUserDefaults] objectForKey:@"isFirstPageDetailVideoHelp"]boolValue];
                imageName = @"home_video_stop_tag";
            }
            if (!isFirstTypeUse) {
                [self setCoverViewWithImg:imageName];
                self.isShow = YES;
            }
        }
    }else{
        [self setCoverViewWithImg:@"home_help_change_tag"];
    }
}

- (void)setCoverViewWithImg:(NSString *)imgName{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.helpCoverView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
        self.helpCoverView.backgroundColor = RGBA(0, 0, 0, 0.7);
        [self.view addSubview:self.helpCoverView];
        
        self.helpNextImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:imgName]];
        [self.helpCoverView addSubview:self.helpNextImgView];
        
        [self.helpNextImgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.helpCoverView);
        }];
        
        self.helpRemoveImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"common_help_tag"]];
        [self.helpCoverView addSubview:self.helpRemoveImgView];
        [self.helpRemoveImgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.helpCoverView).offset(-21);
            make.bottom.equalTo(self.helpCoverView.mas_bottom).offset(-(200 + GK_SAVEAREA_BTM));
        }];
        
        self.helpRemoveImgView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeHelpView)];
        [self.helpRemoveImgView addGestureRecognizer:tap];
        
    });
}

#pragma mark - 设置头部区域
- (void)setupHeaderView{
    
    self.headView = [[HomePageDetailHeaderView alloc]init];
    self.headView.delegate = self;
    [self.view addSubview:self.headView];
   
    self.noDataView = [[HomePageDetailNoDataView alloc]init];
    self.noDataView.delegate = self;
    [self.view addSubview:self.noDataView];
   
    [self.headView showIndexWithCurrentItemModel:self.currentModel];
    
}
#pragma mark - 处理数据
- (void)setupRealDataSource{

}
#pragma mark - 处理通知
- (void)registNote{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateItemStatus:) name:@"updateItemStatus" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateFollowListStatus:) name:@"updateUserInfoFollowListStatus" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateLoginUserInfoFollowListStatus) name:@"updateLoginUserInfoFollowListStatus" object:nil];
}

#pragma mark - 加载更多
- (void)loadMoreData{
    [self loadRequestData];
}

- (void)updateLoginUserInfoFollowListStatus{
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm transactionWithBlock:^{
        RLMResults<UserInfoFollowModel *> *result = [UserInfoFollowModel allObjects];
        if (result.count > 0) {
            for (int index = 0; index < result.count; index++) {
                UserInfoFollowModel *itemModel = result[index];
                [self.dataArray enumerateObjectsUsingBlock:^(HomePageItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([obj.userId isEqualToNumber:@(itemModel.userId)]) {
                        obj.followType = @(itemModel.followCode);
                    }
                }];
            }
        }
        [self.tableView reloadData];
    }];
}

- (void)updateFollowListStatus:(NSNotification *)note{
    MineFollowItemModel *itemModel = note.userInfo[@"data"];
    [self.dataArray enumerateObjectsUsingBlock:^(HomePageItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.userId isEqualToNumber:itemModel.userId]) {
            obj.followType = itemModel.followCode;
        }
    }];
    [self.tableView reloadData];
}

- (void)updateItemStatus:(NSNotification *)note{
    int commentCount = self.currentModel.commentNum.intValue;
    BOOL status = [note.userInfo[@"status"] boolValue];
    if (status) {
        commentCount++;
    }else{
        commentCount--;
    }
    self.currentModel.commentNum = @(commentCount);

    [self.tableView reloadData];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateItemListSource" object:nil userInfo:@{@"data":self.currentModel}];
}
#pragma mark - 设置定时器
- (void)setupTimer{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(updatePageDetailNumber) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    // 暂停
    [self.timer setFireDate:[NSDate distantFuture]];
}
- (void)updatePageDetailNumber{
    [self.timer setFireDate:[NSDate distantFuture]];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"postId"] = self.currentModel.postId;
    param[@"md5"] = [RPAppManager md5StrWithApi:SaveUserViewPost];
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(SaveUserViewPost) parames:param success:^(id responseObj) {
        
    } failure:^(id error) {
            
    }];
    
}
#pragma mark - network
- (void)loadTargetDetailSource{
    
    [self.likeTask cancel];

    NSMutableDictionary *parma = [NSMutableDictionary dictionary];
    parma[@"userId"] = [RPAppManager getCustomerId];
    parma[@"postId"] = self.currentModel.postId;
    parma[@"md5"] = [RPAppManager md5StrWithApi:GetPostTargetDetail];
    self.likeTask = [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetPostTargetDetail) parames:parma success:^(id responseObj) {
        
    } failure:^(NSError *error) {
        __weak typeof(self)weakSelf = self;
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:^{
            if (error.code == 2) {
                [weakSelf dealRemoveMethod];
                // 请求下一条数据
                if (weakSelf.dataArray.count != 0) {
                    [weakSelf loadTargetDetailSource];
                }
            }
        }];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"deleteHomePageItem" object:nil userInfo:@{@"data":self.currentModel}];
    }];
}

- (void)updateShareCountSource{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"postId"] = self.currentModel.postId;
    param[@"md5"] = [RPAppManager md5StrWithApi:UpdatePostShareNum];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(UpdatePostShareNum) parames:param success:^(id responseObj) {
         
        int shareNum = self.currentModel.shareNum.intValue;
        shareNum++;
        self.currentModel.shareNum = @(shareNum);
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateItemListSource" object:nil userInfo:@{@"data":self.currentModel}];
        
        [MobClick event:@"home_detail_share"];
        
        [MobClick event:@"dynamic_share_total" attributes:@{@"page":@"detail"}];
        
        [self.tableView reloadData];
        
    } failure:^(id error) {
            
    }];
}

- (void)loadRequestData{
    
    if (self.lastPage) {
        return;
    }
    // 这里要做判断
    if (self.likeUserInfoId != nil) {
        [self loadLikeListSource];
    }else{
        [self loadMoreListSource];
    }
}

- (void)doDissOrLikeWithStatus:(BOOL)status{
    
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    [self.task1 cancel];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"type"] = status?@1:@2;
    param[@"postId"] = self.currentModel.postId;
    
    if (status) {
        param[@"isTourist"] = self.currentModel.isLike?@1:@2;
    }else{
        param[@"isTourist"] = self.currentModel.isUnLike?@1:@2;
    }
    
    param[@"md5"] = [RPAppManager md5StrWithApi:DoDetailLike];
    self.task1 = [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(DoDetailLike) parames:param success:^(id responseObj) {

        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateItemListSource" object:nil userInfo:@{@"data":self.currentModel}];
        
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
        if (status) {
            NSInteger likeNum = self.currentModel.likeNum.intValue;
            if (self.currentModel.isLike) {
                likeNum--;
            }else{
                likeNum++;
            }
            self.currentModel.likeNum = @(likeNum);
            self.currentModel.isLike = !self.currentModel.isLike;
        }else{
            NSInteger unLikeNum = self.currentModel.unlikeNum.intValue;
            if (self.currentModel.isUnLike) {
                unLikeNum--;
            }else{
                unLikeNum++;
            }
            self.currentModel.unlikeNum = @(unLikeNum);
            self.currentModel.isUnLike = !self.currentModel.isUnLike;
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateItemListSource" object:nil userInfo:@{@"data":self.currentModel}];
        
        [self.tableView reloadRow:self.currentIndex inSection:0 withRowAnimation:UITableViewRowAnimationNone];
    }];
}

#pragma mark - 更新follow状态
- (void)updateFollowStatus:(BOOL)status{

    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    
   
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"followId"] = self.currentModel.userId;
    param[@"type"] = status?@(1):@(2);
    param[@"md5"] = [RPAppManager md5StrWithApi:FollowAndUnFollow];
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(FollowAndUnFollow) parames:param success:^(id responseObj) {
        if (status) {
            [WHToast showMessage:@"关注成功" duration:2 finishHandler:nil];
        }else{
            [WHToast showMessage:@"取消关注" duration:2 finishHandler:nil];
        }
        NSNumber *followType =  responseObj[RESPONSE][@"followCode"];
        
        self.currentModel.followType = followType;
        
        [self.dataArray enumerateObjectsUsingBlock:^(HomePageItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.userId isEqualToNumber:self.currentModel.userId]) {
                obj.followType = followType;
            }
        }];
        
        [self.tableView reloadData];
        
        __block BOOL isLocal = NO;
        RLMRealm *realm = [RLMRealm defaultRealm];
        [realm transactionWithBlock:^{
            RLMResults<UserInfoFollowModel *> *result = [UserInfoFollowModel allObjects];
            if (result.count > 0) {
                for (int index = 0; index < result.count; index++) {
                    UserInfoFollowModel *itemModel = result[index];
                    if (itemModel.userId == self.currentModel.userId.longValue) {
                        itemModel.followCode = self.currentModel.followType.longValue;
                        isLocal = YES;
                        break;
                    }
                }
            }
            if (!isLocal) {
                UserInfoFollowModel *userInfo = [[UserInfoFollowModel alloc]init];
                userInfo.userId = self.currentModel.userId.longValue;
                userInfo.followCode = self.currentModel.followType.longValue;
                userInfo.realName = self.currentModel.realName;
                [realm addOrUpdateObject:userInfo];
            }
        }];
        
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateItemListSource" object:nil userInfo:@{@"data":self.currentModel}];
        
        //隐藏按钮
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
    
}

#pragma mark - method

- (void)removeAllHelpView{
    [self.helpCoverView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.helpCoverView removeFromSuperview];
}


- (void)removeHelpView{
    
    NSString *imgName = @"";
    
    if (!self.isShow) {
        if (self.currentModel.contentType.intValue == 1) {
            self.isShow = [[[NSUserDefaults standardUserDefaults]objectForKey:@"isFirstPageDetailContentHelp"] boolValue];
            imgName = @"home_next_text_tag";
        }else if (self.currentModel.contentType.intValue == 2) {
            self.isShow = [[[NSUserDefaults standardUserDefaults]objectForKey:@"isFirstPageDetailPictureHelp"] boolValue];
            imgName = @"home_next_img_tag";
        }else if (self.currentModel.contentType.intValue == 3) {
            self.isShow = [[[NSUserDefaults standardUserDefaults]objectForKey:@"isFirstPageDetailVideoHelp"] boolValue];
            imgName = @"home_video_stop_tag";
        }
    }
    if (!self.isShow) {
        self.helpNextImgView.image = [UIImage imageNamed:imgName];
        self.isShow = YES;

    }else{
        [self.helpCoverView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self.helpCoverView removeFromSuperview];
        if (self.type != XHPageDetailPlatformTypeHtml) {
            [[NSUserDefaults standardUserDefaults] setObject:@1 forKey:@"isFirstPageDetailUse"];
            [[NSUserDefaults standardUserDefaults]synchronize];
        }
        if (self.currentModel.contentType.intValue == 1) {
            [[NSUserDefaults standardUserDefaults]setObject:@1 forKey:@"isFirstPageDetailContentHelp"];
        }else if (self.currentModel.contentType.intValue == 2) {
            [[NSUserDefaults standardUserDefaults]setObject:@1 forKey:@"isFirstPageDetailPictureHelp"];
        }else if (self.currentModel.contentType.intValue == 3) {
            [[NSUserDefaults standardUserDefaults]setObject:@1 forKey:@"isFirstPageDetailVideoHelp"];
        }
    }
}

- (void)removeMethod{
    
    self.currentModel.isShowAllContent = NO;
    
    [self.player stopCurrentPlayingView];
    
    [self.navigationController popViewControllerAnimated:YES];

}

- (void)deleteMethod{
    
    
    __weak typeof(self)weakSelf = self;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定删除？" message:@"删除后无法恢复" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
        
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"postId"] = weakSelf.currentModel.postId;
        param[@"md5"] = [RPAppManager md5StrWithApi:DeleteDetail];
        [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(DeleteDetail) parames:param success:^(id responseObj) {
            
            if ([self.currentModel.type isEqualToString:@"1"]) {
                [MobClick event:@"mine_delete_dynamic"];
            }else if ([self.currentModel.type isEqualToString:@"2"]){
                [MobClick event:@"mine_delete_work"];
            }else{
                [MobClick event:@"user_delete_dynamic"];
            }

            [weakSelf.player.currentPlayerManager pause];
            
            [[NSNotificationCenter defaultCenter]postNotificationName:@"deleteHomePageItem" object:nil userInfo:@{@"data":weakSelf.currentModel}];
            
            [weakSelf dealRemoveMethod];
            
        } failure:^(id error) {
                        
        }];
        
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
    }];
    [confirmAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
    [cancelAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
             //往alertViewController上添加alertAction
    [alertController addAction:cancelAction];
    [alertController addAction:confirmAction];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
    
    
//    BOOL isDelete = NO;
//
//    if (self.itemType == XHPageDetailItemTypeNormal) {
//        isDelete = NO;
//    }else{
//        // 判断哪里删除
//        if ([[RPAppManager getCustomerId] isEqualToNumber:self.currentModel.userId]) {
//            isDelete = YES;
//        }
//    }
//    if (isDelete) {
//        __weak typeof(self)weakSelf = self;
//        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定删除？" message:@"删除后无法恢复" preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            [alertController dismissViewControllerAnimated:YES completion:nil];
//
//            NSMutableDictionary *param = [NSMutableDictionary dictionary];
//            param[@"postId"] = weakSelf.currentModel.postId;
//            param[@"md5"] = [RPAppManager md5StrWithApi:DeleteDetail];
//            [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(DeleteDetail) parames:param success:^(id responseObj) {
//
//                if ([self.currentModel.type isEqualToString:@"1"]) {
//                    [MobClick event:@"mine_delete_dynamic"];
//                }else if ([self.currentModel.type isEqualToString:@"2"]){
//                    [MobClick event:@"mine_delete_work"];
//                }else{
//                    [MobClick event:@"user_delete_dynamic"];
//                }
//
//                [weakSelf.player.currentPlayerManager pause];
//
//                [[NSNotificationCenter defaultCenter]postNotificationName:@"deleteHomePageItem" object:nil userInfo:@{@"data":weakSelf.currentModel}];
//
//                [weakSelf dealRemoveMethod];
//
//            } failure:^(id error) {
//
//            }];
//
//        }];
//        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            [alertController dismissViewControllerAnimated:YES completion:nil];
//        }];
//        [confirmAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
//        [cancelAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
//                 //往alertViewController上添加alertAction
//        [alertController addAction:cancelAction];
//        [alertController addAction:confirmAction];
//        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
//    }else{
//        /*
//         followType  |int        |0没有相互关系 1关注 2粉丝 3互相关注
//         */
//        __weak typeof(self)weakSelf = self;
//        if (self.currentModel.followType.intValue == 1 || self.currentModel.followType.intValue == 3) {
//            HomePageFollowMoreView *moreView = [[HomePageFollowMoreView alloc]initWithCompleteBlock:^(NSInteger index) {
//                if (index == 2) {
//                    [weakSelf updatePlayerStatus];
//                    [weakSelf.player.currentPlayerManager pause];
//
//                    if (![RPAppManager isLogin]) {
//                        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":weakSelf.navigationController} completion:nil];
//                    }else{
//                        [MobClick event:@"homeDetail_report_click"];
//
//                        [MGJRouter openURL:@"local://ddup/report" withUserInfo:@{@"navigationVC":weakSelf.navigationController,@"reportId":weakSelf.currentModel.postId ,@"reportType":@(0)} completion:nil];
//                    }
//                }else{
//                    [weakSelf updateFollowStatus:NO];
//                    [MobClick event:@"homeDetail_follow_cancel"];
//                }
//            }];
//            [moreView show];
//        }else{
//            HomePageFeedbackView *feedbackView = [[HomePageFeedbackView alloc]initWithCompleteBlock:^{
//                [weakSelf updatePlayerStatus];
//                [weakSelf.player.currentPlayerManager pause];
//                if (![RPAppManager isLogin]) {
//                    [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":weakSelf.navigationController} completion:nil];
//                }else{
//                    [MobClick event:@"homeDetail_report_click"];
//                    [MGJRouter openURL:@"local://ddup/report" withUserInfo:@{@"navigationVC":weakSelf.navigationController,@"reportId":weakSelf.currentModel.postId ,@"reportType":@(0)} completion:nil];
//                }
//            }];
//            [feedbackView show];
//        }
//    }
}

#pragma mark - tableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HomePageItemModel *model = self.dataArray[indexPath.item];
    // 首页进入和动态进入
    model.showUserInfo = self.showUserInfo;
    
    model.showFooterTool = !self.isHideTool;
    
    model.showCreateTime = self.showCreateTime;
   
    if (model.contentType.intValue == 1) {
        HomePageContentDetailCell *cell = [HomePageContentDetailCell cellWithTableView:tableView];
        cell.delegate = self;
        [cell setItemModel:model indexPath:indexPath];
        return cell;
    }
    if (model.contentType.intValue == 2) {
        HomePageDetailImageItemCell *cell = [HomePageDetailImageItemCell cellWithTableView:tableView];
        cell.delegate = self;
        [cell setItemModel:model indexPath:indexPath];
        return cell;
    }
    if (model.contentType.intValue == 3) {
        HomePageDetailVideoItemCell *cell = [HomePageDetailVideoItemCell cellWithTableView:tableView];
        cell.delegate = self;
        [cell setItemModel:model indexPath:indexPath];
        return cell;
    }
    HomePageContentDetailCell *cell = [HomePageContentDetailCell cellWithTableView:tableView];
    return cell;
}

#pragma mark - HomePageDetailImageItemCellDelegate
-(void)imageItemLongPressToolView{
    NSMutableArray *itemArray = [NSMutableArray array];
    
    HomePageMenuItemModel *itemModel = [[HomePageMenuItemModel alloc]init];
    itemModel.mainTitle = @"保存到相册";
    itemModel.itemType = XHMENUITEMSAVEPICTURE;
    [itemArray addObject:itemModel];
    
    BOOL isDelete = [self isDeleteMenu];
    if (isDelete) {
        HomePageMenuItemModel *itemModel3 = [[HomePageMenuItemModel alloc]init];
        itemModel3.mainTitle = @"删除";
        itemModel3.itemType = XHMENUITEMDELETE;
        [itemArray addObject:itemModel3];
    }else{
        if (self.currentModel.followType.intValue == 1 || self.currentModel.followType.intValue == 3) {
            HomePageMenuItemModel *itemModel1 = [[HomePageMenuItemModel alloc]init];
            itemModel1.mainTitle = @"取消关注";
            itemModel1.subTitle = @"不再关注TA";
            itemModel1.itemType = XHMENUITEMCANCELFOLLOW;
            [itemArray addObject:itemModel1];
        }
        HomePageMenuItemModel *itemModel2 = [[HomePageMenuItemModel alloc]init];
        itemModel2.mainTitle = @"投诉";
        itemModel2.itemType = XHMENUITEMREPORT;
        [itemArray addObject:itemModel2];
    }
    
    __weak typeof(self)weakSelf = self;
    HomePageMenuView *menuView = [[HomePageMenuView alloc]initWithItemArray:itemArray completeBlock:^(XHMenuItemType type) {
        // 取消关注
        if (type == XHMENUITEMCANCELFOLLOW) {
            [weakSelf updateFollowStatus:NO];
            [MobClick event:@"homeDetail_follow_cancel"];
        }
        // 投诉
        if (type == XHMENUITEMREPORT) {
            if (![RPAppManager isLogin]) {
                [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":weakSelf.navigationController} completion:nil];
            }else{
                [MobClick event:@"homeDetail_report_click"];
                [MGJRouter openURL:@"local://ddup/report" withUserInfo:@{@"navigationVC":weakSelf.navigationController,@"reportId":weakSelf.currentModel.postId ,@"reportType":@(0)} completion:nil];
            }
        }
        if (type == XHMENUITEMSAVEPICTURE) {
            
            if (![RPAppManager checkVideoPhotoAuthorization]) {
                [self setAuthStatusWithMessage:@"此功能需要您授权本App打开照片\n设置方法: 打开手机设置->隐私->照片"];
                return;
            }
            
            NSArray *urls = self.currentModel.urls;
            
            SDWebImageManager *manager = [SDWebImageManager sharedManager];
            NSString* key = [manager cacheKeyForURL:[NSURL URLWithString:urls[self.currentModel.currentIndex]]];
            SDImageCache* cache = [SDImageCache sharedImageCache];
            //此方法会先从memory中取。
            UIImage *image = [cache imageFromDiskCacheForKey:key];
            if (image != nil) {
                UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
            }
        }
        if (type == XHMENUITEMDELETE) {
            [self deleteMethod];
        }
    }];
    [menuView show];
}


- (void)setAuthStatusWithMessage:(NSString *)message{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
        // 去设置相册权限
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication]canOpenURL:url]) {
            [[UIApplication sharedApplication]openURL:url options:@{} completionHandler:nil];
        }
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
    }];
    [confirmAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
    [cancelAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
    //往alertViewController上添加alertAction
    [alertController addAction:cancelAction];
    [alertController addAction:confirmAction];
    [self presentViewController:alertController animated:YES completion:nil];
    
}


- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error == nil) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_success"] message:@"成功保存至手机" duration:2 finishHandler:nil];
    }else{
        [WHToast showMessage:@"保存失败" duration:2 finishHandler:nil];
    }
}


- (void)imageItemShowHideToolView{
    self.isHideTool = !self.isHideTool;
        
    if (self.isHideTool) {
        [MobClick event:@"homeDetail_hide_statusBar"];
    }
    
    [UIView animateWithDuration:0.25 animations:^{
        self.headView.cl_y = self.isHideTool?-kNavBarHeight:0;
    } completion:^(BOOL finished) {
        
    }];
}
- (void)imageItemLikeWithCurrentModel:(HomePageItemModel *)currentModel{
    self.currentModel = currentModel;
    [self doDissOrLikeWithStatus:YES];
}
- (void)imageItemDissWithCurrentModel:(HomePageItemModel *)currentModel{
    self.currentModel = currentModel;
    [self doDissOrLikeWithStatus:NO];
}

- (void)imageItemFollowWithCurrentModel:(HomePageItemModel *)currentModel{
    self.currentModel = currentModel;
    [self updateFollowStatus:YES];
}
- (void)imageItemUserInfoWithCurrentModel:(HomePageItemModel *)currentModel{
    [MGJRouter openURL:@"local://ddup/homePage/userInfo" withUserInfo:@{@"navigationVC":self.navigationController,@"loadType":@(1),@"userId":currentModel.userId} completion:nil];

}
- (void)imageItemScrollViewEnabale:(BOOL)isEnable{
    self.tableView.scrollEnabled = isEnable;
    if (self.type == XHPageDetailPlatformTypeMessageComment ||
        self.type == XHPageDetailPlatformTypeMessageReply ||
        self.type == XHPageDetailPlatformTypeHtml ||
        self.type == XHPageDetailPlatformTypeSingleDetail ||
        self.type == XHPageDetailPlatformTypeMessageOther) {
        self.tableView.scrollEnabled = NO;
    }
}

- (void)imageItemCommentWithCurrentModel:(HomePageItemModel *)currentModel{
   
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    self.type = XHPageDetailPlatformTypeShowComment;
    if (currentModel.commentNum.intValue == 0) {
        self.type = XHPageDetailPlatformTypeBeginText;
    }
    self.commentView = [[HomePageCommentView alloc]initWithPlatformId:self.currentModel.postId platformType:self.type showCommentId:@0 showReplyId:@0];
    [self.commentView showBindVC:self delegate:self];
    
}
- (void)imageItemTopicListWithCurrentModel:(HomeTagItemModel *)currentModel{
    HomePageTopicListViewController *vc = [[HomePageTopicListViewController alloc]init];
    vc.tagModel = currentModel;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)imageItemSelectAtIndex:(NSInteger)currentIndex{
    
    [self.headView showIndexWithCurrentItemModel:self.currentModel];

}

#pragma mark - HomePageContentDetailCellDelegate

- (void)contentItemSelectAtIndex:(NSInteger)currentIndex{
    [self.headView showIndexWithCurrentItemModel:self.currentModel];
}

- (void)contentItemLongPressToolView{
    NSMutableArray *itemArray = [NSMutableArray array];
    
    BOOL isDelete = [self isDeleteMenu];
    if (isDelete) {
        HomePageMenuItemModel *itemModel = [[HomePageMenuItemModel alloc]init];
        itemModel.mainTitle = @"删除";
        itemModel.itemType = XHMENUITEMDELETE;
        [itemArray addObject:itemModel];
    }else{
        if (self.currentModel.followType.intValue == 1 || self.currentModel.followType.intValue == 3) {
            HomePageMenuItemModel *itemModel = [[HomePageMenuItemModel alloc]init];
            itemModel.mainTitle = @"取消关注";
            itemModel.subTitle = @"不再关注TA";
            itemModel.itemType = XHMENUITEMCANCELFOLLOW;
            [itemArray addObject:itemModel];
        }
        HomePageMenuItemModel *itemModel1 = [[HomePageMenuItemModel alloc]init];
        itemModel1.mainTitle = @"投诉";
        itemModel1.itemType = XHMENUITEMREPORT;
        [itemArray addObject:itemModel1];
    }
    
    __weak typeof(self)weakSelf = self;
    HomePageMenuView *menuView = [[HomePageMenuView alloc]initWithItemArray:itemArray completeBlock:^(XHMenuItemType type) {
        // 取消关注
        if (type == XHMENUITEMCANCELFOLLOW) {
            [weakSelf updateFollowStatus:NO];
            [MobClick event:@"homeDetail_follow_cancel"];
        }
        // 投诉
        if (type == XHMENUITEMREPORT) {
            if (![RPAppManager isLogin]) {
                [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":weakSelf.navigationController} completion:nil];
            }else{
                [MobClick event:@"homeDetail_report_click"];
                [MGJRouter openURL:@"local://ddup/report" withUserInfo:@{@"navigationVC":weakSelf.navigationController,@"reportId":weakSelf.currentModel.postId ,@"reportType":@(0)} completion:nil];
            }
        }
        if (type == XHMENUITEMDELETE) {
            [weakSelf deleteMethod];
        }
    }];
    [menuView show];

}

// 首先判断是否是删除功能的菜单栏
- (BOOL)isDeleteMenu{
    if (self.type == XHPageDetailPlatformTypeMineList) {
        return YES;
    }
    if (self.itemType == XHPageDetailItemTypeMix) {
        if ([RPAppManager isLogin] && [[RPAppManager getCustomerId] isEqualToNumber:self.currentModel.userId]) {
            return YES;
        }
        return NO;
    }
    return NO;
}


- (void)contentItemShowHideToolView{
    self.isHideTool = !self.isHideTool;
    [UIView animateWithDuration:0.25 animations:^{
        self.headView.cl_y = self.isHideTool?-kNavBarHeight:0;
    } completion:^(BOOL finished) {
        
    }];
}
- (void)contentItemLikeWithCurrentModel:(HomePageItemModel *)currentModel{
    self.currentModel = currentModel;
    [self doDissOrLikeWithStatus:YES];
}
- (void)contentItemDissWithCurrentModel:(HomePageItemModel *)currentModel{
    self.currentModel = currentModel;
    [self doDissOrLikeWithStatus:NO];
}
- (void)contentItemFollowWithCurrentModel:(HomePageItemModel *)currentModel{
    self.currentModel = currentModel;
    [self updateFollowStatus:YES];
}
- (void)contentItemShowUserInfoWithCurrentModel:(HomePageItemModel *)currentModel{
    [MGJRouter openURL:@"local://ddup/homePage/userInfo" withUserInfo:@{@"navigationVC":self.navigationController,@"loadType":@(1),@"userId":currentModel.userId} completion:nil];
}
- (void)contentItemTopicListWithCurrentTopicModel:(HomeTagItemModel *)currentModel{
    HomePageTopicListViewController *vc = [[HomePageTopicListViewController alloc]init];
    vc.tagModel = currentModel;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)contentItemCommentInfoWithCurrentModel:(HomePageItemModel *)currentModel{
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    
    self.type = XHPageDetailPlatformTypeShowComment;
    if (currentModel.commentNum.intValue == 0) {
        self.type = XHPageDetailPlatformTypeBeginText;
    }
    self.commentView = [[HomePageCommentView alloc]initWithPlatformId:self.currentModel.postId platformType:self.type showCommentId:@0 showReplyId:@0];
    [self.commentView showBindVC:self delegate:self];
}

#pragma mark - HomePageDetailVideoItemCellDelegate

- (void)videoItemLongPressToolView{
    NSMutableArray *itemArray = [NSMutableArray array];
    
    BOOL isDelete = [self isDeleteMenu];
    if (isDelete) {
        HomePageMenuItemModel *itemModel = [[HomePageMenuItemModel alloc]init];
        itemModel.mainTitle = @"删除";
        itemModel.itemType = XHMENUITEMDELETE;
        [itemArray addObject:itemModel];
    }else{
        if (self.currentModel.followType.intValue == 1 || self.currentModel.followType.intValue == 3) {
            HomePageMenuItemModel *itemModel = [[HomePageMenuItemModel alloc]init];
            itemModel.mainTitle = @"取消关注";
            itemModel.subTitle = @"不再关注TA";
            itemModel.itemType = XHMENUITEMCANCELFOLLOW;
            [itemArray addObject:itemModel];
        }
        HomePageMenuItemModel *itemModel1 = [[HomePageMenuItemModel alloc]init];
        itemModel1.mainTitle = @"投诉";
        itemModel1.itemType = XHMENUITEMREPORT;
        [itemArray addObject:itemModel1];
    }
    
    __weak typeof(self)weakSelf = self;
    HomePageMenuView *menuView = [[HomePageMenuView alloc]initWithItemArray:itemArray completeBlock:^(XHMenuItemType type) {
        // 取消关注
        if (type == XHMENUITEMCANCELFOLLOW) {
            [weakSelf updateFollowStatus:NO];
            [MobClick event:@"homeDetail_follow_cancel"];
        }
        // 投诉
        if (type == XHMENUITEMREPORT) {
            if (![RPAppManager isLogin]) {
                [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":weakSelf.navigationController} completion:nil];
            }else{
                [MobClick event:@"homeDetail_report_click"];
                [MGJRouter openURL:@"local://ddup/report" withUserInfo:@{@"navigationVC":weakSelf.navigationController,@"reportId":weakSelf.currentModel.postId ,@"reportType":@(0)} completion:nil];
            }
        }
        if (type == XHMENUITEMDELETE) {
            [weakSelf deleteMethod];
        }
    }];
    [menuView show];
}

- (void)videoItemLikeWithCurrentModel:(HomePageItemModel *)currentModel{
    self.currentModel = currentModel;
    [self doDissOrLikeWithStatus:YES];
}

- (void)videoItemDissWithCurrentModel:(HomePageItemModel *)currentModel{
    self.currentModel = currentModel;
    [self doDissOrLikeWithStatus:NO];
}
- (void)videoItemFollowWithCurrentModel:(HomePageItemModel *)currentModel{
    self.currentModel = currentModel;
    [self updateFollowStatus:YES];
}
-(void)videoItemUserInfoWithCurrentModel:(HomePageItemModel *)currentModel{
    [MGJRouter openURL:@"local://ddup/homePage/userInfo" withUserInfo:@{@"navigationVC":self.navigationController,@"loadType":@(1),@"userId":currentModel.userId} completion:nil];
}

- (void)videoItemChangeProgressValue:(CGFloat)value{
    int currentTime = self.player.totalTime*value;
    int totalTime = self.player.totalTime;
    self.totalTimeLb.text = [NSString stringWithFormat:@"  /  %02d:%02d",totalTime/60,totalTime%60];
    self.currenTimeLb.text = [NSString stringWithFormat:@"%02d:%02d",currentTime/60,currentTime%60];
    [UIView animateWithDuration:0.25 animations:^{
        self.totalTimeLb.alpha = 1;
        self.currenTimeLb.alpha = 1;
    }];

}

- (void)videoItemUpdateProgressValue:(CGFloat)value{
    self.isDraging = NO;
    [UIView animateWithDuration:0.25 animations:^{
        self.totalTimeLb.alpha = 0;
        self.currenTimeLb.alpha = 0;
    }];
    @zf_weakify(self)
    [self.player seekToTime:self.player.totalTime*value completionHandler:^(BOOL finished) {
        @zf_strongify(self)
        if (finished) {
            self.isUpdateProgress = YES;
        }
    }];
}
- (void)videoItemScrollViewEnabale:(BOOL)isEnable{
    
    self.tableView.scrollEnabled = isEnable;
    if (self.type == XHPageDetailPlatformTypeMessageComment ||
        self.type == XHPageDetailPlatformTypeMessageReply ||
        self.type == XHPageDetailPlatformTypeHtml ||
        self.type == XHPageDetailPlatformTypeSingleDetail ||
        self.type == XHPageDetailPlatformTypeMessageOther) {
        self.tableView.scrollEnabled = NO;
    }
}


- (void)videoItemCommentWithCurrentModel:(HomePageItemModel *)currentModel{
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    self.type = XHPageDetailPlatformTypeShowComment;
    if (currentModel.commentNum.intValue == 0) {
        self.type = XHPageDetailPlatformTypeBeginText;
    }
    self.commentView = [[HomePageCommentView alloc]initWithPlatformId:self.currentModel.postId platformType:self.type showCommentId:@0 showReplyId:@0];
    [self.commentView showBindVC:self delegate:self];
}
- (void)videoItemTopicListWithCurrentModel:(HomeTagItemModel *)currentModel{
    HomePageTopicListViewController *vc = [[HomePageTopicListViewController alloc]init];
    vc.tagModel = currentModel;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)videoItemBeginDraging{
    self.isDraging = YES;
    self.isUpdateProgress = NO;
}

#pragma mark - UIScrollViewDelegate   列表播放必须实现

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    [scrollView zf_scrollViewDidEndDecelerating];

    NSInteger index = scrollView.contentOffset.y/kScreenH;
   
    HomePageItemModel *currentModel = self.dataArray[index];
    if (![currentModel.postId isEqualToNumber:self.currentModel.postId]) {
        self.currentModel.currentIndex = 0;
        NSInteger index = [self.dataArray indexOfObject:self.currentModel];
        [self.tableView reloadRow:index inSection:0 withRowAnimation:UITableViewRowAnimationNone];
        self.currentModel = currentModel;
    }
    if (self.likeUserInfoId != nil) {
        [self loadTargetDetailSource];
    }

    [self.headView showIndexWithCurrentItemModel:self.currentModel];

    
    if (index != self.currentIndex) {
        [self.timer setFireDate:[NSDate date]];
        self.currentIndex = index;
    }
    
    self.playStatus = @0;
 
    [self setupHelpCoverView];
 
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [scrollView zf_scrollViewDidEndDraggingWillDecelerate:decelerate];
    NSInteger index = scrollView.contentOffset.y/kScreenH;
    if (scrollView.contentOffset.y <= 0) {
        [WHToast showMessage:@"已是第一个" duration:2 finishHandler:nil];
        return;
    }
    if (index == self.dataArray.count - 1 && self.lastPage) {
        [WHToast showMessage:@"没有更多了" duration:2 finishHandler:nil];
    }
}

- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewDidScrollToTop];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewDidScroll];
    
    int index = scrollView.contentOffset.y/kScreenH;

    if (index == self.dataArray.count - 3 && !self.lastPage) {
        if (self.task != nil && self.task.state == NSURLSessionTaskStateRunning) {
            return;
        }else{
            [self loadRequestData];
        }
    }
    
    if (index == self.dataArray.count - 1 && !self.lastPage) {
        if (self.task != nil && self.task == NSURLSessionTaskStateRunning) {
            return;
        }
        [self loadRequestData];
    }
    self.isUpdateProgress = YES;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.playStatus = @0;
    self.lastIndexPath = nil;
    [scrollView zf_scrollViewWillBeginDragging];
    [self.timer setFireDate:[NSDate distantFuture]];
}
#pragma mark - ZFTableViewCellDelegate

- (void)zf_playTheVideoAtIndexPath:(NSIndexPath *)indexPath {
    [self playTheVideoAtIndexPath:indexPath scrollAnimated:NO];
}

#pragma mark - private method
/// play the video
- (void)playTheVideoAtIndexPath:(NSIndexPath *)indexPath scrollAnimated:(BOOL)animated {

    
    if (self.playStatus.intValue == 2) {
        return;
    }
    
    if (self.player.currentPlayerManager.playState == ZFPlayerPlayStatePaused) {
        [self.player.currentPlayerManager play];
        return;
    }
    if (self.player.currentPlayerManager.playState == ZFPlayerPlayStatePlaying) {
        return;
    }
    
    
  
    HomePageItemModel *model = self.dataArray[indexPath.item];
    
    __block HomePageContentModel *imageItem = nil;
    __block HomePageContentModel *videoItem = nil;
    
    [model.contents enumerateObjectsUsingBlock:^(HomePageContentModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.seq.intValue == 1) {
            imageItem = obj;
        }
        if (obj.seq.intValue == 2) {
            videoItem = obj;
        }
    }];
    
    
    [self.fullControlView coverURLString:imageItem.postUrl fullScreenMode:ZFFullScreenModeLandscape appeared:!self.isHideTool];
    
    self.currentVideoCell = [self.tableView cellForRowAtIndexPath:indexPath];
    
    
    NSString *url = videoItem == nil?@"":videoItem.postUrl;

    if (animated) {
        [self.player playTheIndexPath:indexPath assetURL:[NSURL URLWithString:url] scrollPosition:ZFPlayerScrollViewScrollPositionTop animated:YES];
    } else {
        [self.player playTheIndexPath:indexPath assetURL:[NSURL URLWithString:url]];
    }
}

#pragma mark - HomePageCommentViewDelegate
- (void)loadMorePersonListWithKey:(NSString *)keyword{
    self.userPageIndex++;
    [self loadPersonLishWithKeyWord:keyword page:self.userPageIndex];
}
- (void)getCommentPersonListWithKey:(NSString *)keyword{
    self.userPageIndex = 1;
    [self loadPersonLishWithKeyWord:keyword page:1];
}

- (void)dismissCommentView{
//    [self.headView insertGradientLayerAtIndex:0];
    if (self.type == XHPageDetailPlatformTypeShowComment ||
        self.type == XHPageDetailPlatformTypeShowReply ||
        self.type == XHPageDetailPlatformTypeBeginText) {
        [self setupHelpCoverView];
    }else{
        [self setupOtherCoverView];
    }
}

- (void)loadPersonLishWithKeyWord:(NSString *)keyword page:(NSInteger)page{
    [self.followTask cancel];
    // 请求关注列表
    if (keyword.length == 1 && [keyword isEqualToString:@"@"]) {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"userId"] = [RPAppManager getCustomerId];
        param[@"md5"] = [RPAppManager md5StrWithApi:GetAllFollow];
        param[@"pageSize"] = @(10);
        param[@"pageIndex"] = @(page);
        self.followTask = [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(GetAllFollow) parames:param success:^(id responseObj) {
          
            if (self.userPageIndex == 1) {
                self.userArray = [UserInfoModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
            }else{
                [self.userArray addObjectsFromArray:[UserInfoModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]]];
            }
    
            if ([responseObj[RESPONSE][LASTPAGE] boolValue] || ![responseObj[RESPONSE][NEXTPAGE]boolValue]) {
                [self.commentView updateRefreshFooterState];
            }
            
            [self.commentView refreshUsers:self.userArray];
           
        } failure:^(id error) {
            
        }];
    }else{
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"md5"] = [RPAppManager md5StrWithApi:GetUserListByName];
        param[@"name"] = keyword;
        param[@"userId"] = [RPAppManager getCustomerId];
        param[@"pageSize"] = @(10);
        param[@"pageIndex"] = @(page);
        self.followTask = [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(GetUserListByName) parames:param success:^(id responseObj) {
            if (self.userPageIndex == 1) {
                self.userArray = [UserInfoModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
            }else{
                [self.userArray addObjectsFromArray:[UserInfoModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]]];
            }
            if ([responseObj[RESPONSE][LASTPAGE] boolValue] || ![responseObj[RESPONSE][NEXTPAGE]boolValue]) {
                [self.commentView updateRefreshFooterState];
            }
            
            __block NSInteger index = -1;
            
            [self.userArray enumerateObjectsUsingBlock:^(UserInfoModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj.id isEqualToNumber:[RPAppManager getCustomerId]]) {
                    index = idx;
                    *stop = YES;
                }
            }];
        
            if (index != -1) {
                [self.userArray removeObjectAtIndex:index];
            }
            
            [self.commentView refreshUsers:self.userArray];
    
        } failure:^(id error) {
            
        }];
    }
}

#pragma mark - 分享统一方法
- (void)commonShareWithCurrentModel:(HomePageItemModel *)itemModel{
    if ([RPAppManager isShowNetworkView]) {
        [WHToast showErrorWithMessage:@"网络好像有点问题，请检查后重试" duration:2 finishHandler:nil];
        return;
    }
    [RPAppShareView showCompleteblock:^(XHShareViewPlatformType platformType) {
        UMSocialPlatformType type = UMSocialPlatformType_UnKnown;
        switch (platformType) {
            case XHShareViewPlatformTypeWeChatSession:
                type = UMSocialPlatformType_WechatSession;
                break;
            case XHShareViewPlatformTypeWeChatMoments:
                type = UMSocialPlatformType_WechatTimeLine;
                break;
            case XHShareViewPlatformTypeQQ:
                type = UMSocialPlatformType_QQ;
                break;
                
            case XHShareViewPlatformTypeQQZone:
                type = UMSocialPlatformType_Qzone;
                break;
            
            case XHShareViewPlatformTypeQQWeibo:
                type = UMSocialPlatformType_Sina;
                break;
            default:
                break;
        }
        if (![[UMSocialManager defaultManager] isInstall:type]) {
            if (type == UMSocialPlatformType_WechatSession || type == UMSocialPlatformType_WechatTimeLine) {
                [WHToast showMessage:@"请先安装微信" duration:2 finishHandler:nil];
            }
            if (type == UMSocialPlatformType_QQ || type == UMSocialPlatformType_Qzone) {
                [WHToast showMessage:@"请先安装QQ" duration:2 finishHandler:nil];
            }
            if (type == UMSocialPlatformType_Sina) {
                [WHToast showMessage:@"请先安装微博" duration:2 finishHandler:nil];
            }
            return;
        }
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];

        NSString *title = itemModel.contentText.length == 0?@"DDup":itemModel.contentText;
        
        
        NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];

        NSString *icon = [[infoPlist valueForKeyPath:@"CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles"] lastObject];

        UIImage *shareImage= [UIImage imageNamed:icon];
        
        
        
        NSString* thumbURL =  @"";
        // 文字
        if (itemModel.contentType.intValue == 1) {
            
        // 图片
        }else if(itemModel.contentType.intValue == 2){
            thumbURL = itemModel.urls.firstObject;
        // 视频
        }else{
            __block HomePageContentModel *imageModel = nil;
            [itemModel.contents enumerateObjectsUsingBlock:^(HomePageContentModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (obj.seq.intValue == 1) {
                    imageModel = obj;
                    *stop = YES;
                }
            }];
            thumbURL = imageModel.postUrl;
            
        }
        //创建网页内容对象
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:@"分享我的Chinese高考" thumImage:itemModel.contentType.intValue == 1?shareImage:thumbURL];
        //设置网页地址
        shareObject.webpageUrl = [NSString stringWithFormat:@"%@dynamic?postId=%@",HtmlUrl,itemModel.postId];
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:type messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
                UMSocialLogInfo(@"************Share fail with error %@*********",error);
            }else{
                
            }
        }];
        [self updateShareCountSource];
    }];
}

- (void)updatePlayerStatus{
    if (self.player.currentPlayerManager.isPlaying) {
        self.playStatus = @(1);
    }else{
        self.playStatus = @(2);
    }
}

#pragma mark - 处理删除的操作
- (void)dealRemoveMethod{
    __block NSInteger index = -1;
    [self.dataArray enumerateObjectsUsingBlock:^(HomePageItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.postId isEqualToNumber:self.currentModel.postId]) {
            index = idx;
            *stop = YES;
        }
    }];
    if (index != -1) {
        
        [self.player stopCurrentPlayingCell];
        
        if (self.dataArray.count == 1) {
            [self.dataArray removeObjectAtIndex:index];
        }else{
            // 头
            if (index == 0) {
                self.currentModel = self.dataArray[1];
            }else if (index == self.dataArray.count - 1){
                self.currentModel = self.dataArray[self.dataArray.count - 2];
            }else{
                self.currentModel = self.dataArray[index+1];
            }
            [self.dataArray removeObjectAtIndex:index];
        }
        
        [self.headView showIndexWithCurrentItemModel:self.currentModel];
        
        if (index == self.dataArray.count - 3 && !self.lastPage) {
            if (self.task != nil && self.task.state == NSURLSessionTaskStateRunning) {
                [self.task cancel];
            }else{
                [self loadRequestData];
            }
        }
        self.currentModel.currentIndex = 0;
    }
    [self.tableView reloadData];
    if (self.dataArray.count == 0) {
        [self.player stopCurrentPlayingCell];
        [self removeMethod];
    }else{
        if (self.currentModel.contentType.intValue == 3) {
            NSInteger index = [self.dataArray indexOfObject:self.currentModel];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
            [self playTheVideoAtIndexPath:indexPath scrollAnimated:NO];
        }
    }

    if (self.itemType == XHPageDetailItemTypeMix) {
        [self setupRealDataSource];
    }
}

#pragma mark - headerDelegate
- (void)homePageShareAction{
    [self commonShareWithCurrentModel:self.currentModel];
}
- (void)homePageRemoveAction{
    [self removeMethod];
}

#pragma mark - HomePageDetailNoDataViewDelegate
- (void)noDataBackMethod{
    [self removeMethod];
}

- (void)dealloc{
    
}


#pragma mark ------------------
- (void)loadLikeListSource{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    NSInteger page = ceil(self.dataArray.count/30.0f) + 1;
    
    param[@"pageIndex"] = @(page);
    param[@"pageSize"] = @(30);
    param[@"userId"] = self.likeUserInfoId;
    param[@"loginId"] = [RPAppManager getCustomerId];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetLikePost];
    self.task = [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetLikePost) parames:param success:^(id responseObj) {
        NSArray *resultArray = responseObj[RESPONSE][LIST];
        if ([resultArray isKindOfClass:[NSArray class]] && resultArray.count != 0) {
            [self.dataArray addObjectsFromArray:[HomePageItemModel mj_objectArrayWithKeyValuesArray:resultArray]];
            [self.tableView reloadData];
        }else{
            self.lastPage = YES;
        }
      
        
    } failure:^(id error) {
        
    }];
}

- (void)loadMoreListSource{
    NSInteger page = ceil(self.dataArray.count/10.0f) + 1;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"pageIndex"] = @(page);
    param[@"pageSize"] = @(10);
    param[@"tagId"] = self.tagId;
    param[@"type"] = self.currentModel.type;
    // 我的个人中心或者点击头像进入
    NSString *api = @"";
    NSString *md5 = @"";
    if (self.type == XHPageDetailPlatformTypeUserList) {
        param[@"checked"] = @1;
        param[@"postId"] = self.currentModel.userId;
        md5 = [RPAppManager md5StrWithApi:GetUserPostList];
        api = GetUserPostList;
    }else if(self.type == XHPageDetailPlatformTypeMineList){
        md5 = [RPAppManager md5StrWithApi:GetUserPostList];
        api = GetUserPostList;
        param[@"postId"] = self.currentModel.userId;
    }else{
        md5 = [RPAppManager md5StrWithApi:GetIndexPostList];;
        api = GetIndexPostList;
    }
    self.task = [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(api) parames:param success:^(id responseObj) {

        NSArray *resultArray = responseObj[RESPONSE][LIST];
        if ([resultArray isKindOfClass:[NSArray class]] && resultArray.count != 0) {
            [self.dataArray addObjectsFromArray:[HomePageItemModel mj_objectArrayWithKeyValuesArray:resultArray]];
            [self.tableView reloadData];
        }else{
            self.lastPage = YES;
        }
    
    } failure:^(id error) {
    }];
}
- (void)isExistCommentDetail{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"commentId"] = self.commentId;
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetPostComment];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetPostComment) parames:param success:^(id responseObj) {
        self.commentView = [[HomePageCommentView alloc]initWithPlatformId:self.currentModel.postId platformType:self.type showCommentId:self.commentId showReplyId:self.replyId];
        [self.commentView showBindVC:self delegate:self];
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
        
    }];
}
- (void)isExistReplyDetail{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"replyId"] = self.replyId;
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetCommentReply];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetCommentReply) parames:param success:^(id responseObj) {
        
        self.commentView = [[HomePageCommentView alloc]initWithPlatformId:self.currentModel.postId platformType:self.type showCommentId:self.commentId showReplyId:self.replyId];
        [self.commentView showBindVC:self delegate:self];
     
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}

@end
